<?php
/**
 * 优惠券控制器
 * User: ws
 * Date: 2018/9/27
 * Time: 17:07
 */

namespace app\admin\controller;
use app\admin\model\Coupons as CModeL;
use app\admin\model\Materiel as MModeL;
use think\Db;
class Coupons   extends Init
{
    function index(){
        if ($this->request->isAjax()) {
            $key = input('key')?input('key'):'';

            if(is_numeric(input('coupons_type')) === true){
                $where['coupons_type'] = input('coupons_type');
            }
            if(is_numeric(input('state')) === true){
                $where['state'] = input('state');
            }
            $where['name'] = array('like','%'.trim($key).'%');

            $list = CModeL::where($where)->order('coupons_id desc')->paginate(input('limit'))->toArray();
            foreach ($list['data'] as $key=>$v){
                if($v['scope']==0){
                    $list['data'][$key]['scope'] = '会员卡';
                }elseif($v['scope']==1){
                    $list['data'][$key]['scope'] = '共享商品';
                }elseif($v['scope']==2){
                    $list['data'][$key]['scope'] = '销售商品';
                }else{
                    $list['data'][$key]['scope'] = '销售商品--'.$name =  MModeL::where("materiel_id={$v['scope']}")->value('name');
                }

                $couponsUse = db('coupons_use')->where('coupons_id',$v['coupons_id'])->find();
                if($couponsUse){$list['data'][$key]['use'] = 1;}else{$list['data'][$key]['use'] = 0;}
            }
            return json($result = ['code'=>0,'msg'=>'获取成功','data'=>$list['data'],'count'=>$list['total']]);
        }
        return view('list');
    }


    function add(){
        if(request()->isPost()){
            $data = $this->request->post();
            if($data['limits'] == 1) {
                if (empty($data['limitss']))
                    return json(array('code' => 0, 'msg' => '添加失败,限领值不能为空'));
                $data['limits'] = $data['limitss'];
            }

            if(empty($data['start_time']) || empty($data['settlement_time'])){
                return json(array('code'=>0,'msg'=>'添加失败,使用期限不能为空'));
            }
            unset($data['limitss']);

            if (!CModeL::create($data)) {
                return json(array('code'=>0,'msg'=>'添加失败'));
            }
            return json(array('code'=>200,'msg'=>'添加成功'));
        }
        $materiel = self::choice();
        return view('add',['materiel'=>$materiel]);
    }



    function edit(){
        if(request()->isPost()){
            $data = $this->request->post();
            if($data['limits'] == 1) {
                if (empty($data['limitss']))
                    return json(array('code' => 0, 'msg' => '添加失败,限领值不能为空'));
                $data['limits'] = $data['limitss'];
            }

            if(empty($data['start_time']) || empty($data['settlement_time'])){
                return json(array('code'=>0,'msg'=>'添加失败,使用期限不能为空'));
            }
            unset($data['limitss']);

            if (!CModeL::update($data)) {
                return json(array('code'=>0,'msg'=>'修改失败'));
            }
            return json(array('code'=>200,'msg'=>'修改成功'));
        }

        $list = CModeL::where('coupons_id', input('id'))->find()->toArray();
        $materiel = self::choice($list['scope']);
        return view('edit',['list'=>$list,'materiel'=>$materiel]);
    }


    function del(){
        $id = input('param.id');
        $data = Db::name('coupons_use')->where('coupons_id',$id)->find();
        if($data){
            return json(array('code'=>0,'msg'=>'删除失败，已领取不能被删除'));
        }
        if (!CModeL::destroy(['coupons_id' => $id])) {
            return json(array('code'=>0,'msg'=>'删除失败'));
        }
        return json(array('code'=>200,'msg'=>'删除成功'));
    }



    function index2(){
        if ($this->request->isAjax()) {
            $key = input('key')?input('key'):'';

            if(is_numeric(input('coupons_type')) === true){
                $where['c.coupons_type'] = input('coupons_type');
            }
            if(is_numeric(input('state')) === true){
                $where['u.state'] = input('state');
            }
            $where['c.name|us.name'] = array('like','%'.trim($key).'%');

            $list = db('coupons_use')->alias('u')->join('je_coupons c','u.coupons_id = c.coupons_id')->join('je_user us','u.user_id = us.user_id')->field('us.name as uname,u.*,c.coupons_type,c.name,c.conditions,c.discount,c.settlement_time,c.scope,c.number')->where($where)->order('use_id desc')->paginate(input('limit'))->toArray();
            foreach ($list['data'] as $key=>$v){
                if($v['scope']==0){
                    $list['data'][$key]['scope'] = '会员卡';
                }elseif($v['scope']==1){
                    $list['data'][$key]['scope'] = '共享商品';
                }elseif($v['scope']==2){
                    $list['data'][$key]['scope'] = '销售商品';
                }else{
                    $list['data'][$key]['scope'] = '销售商品--'.$name =  MModeL::where("materiel_id={$v['scope']}")->value('name');
                }


                $list['data'][$key]['card_order'] = '';$list['data'][$key]['order'] = '';
                if($v['state'] == 1){
                    $map['use_id'] = $v['use_id'];
                    $map['order_status'] = array('not in',[0,4]);
                    $card_order = db('card_order')->where("use_id={$v['use_id']} and card_status=1")->field('add_time,card_order_sn,card_order_id')->find();
                    if(!empty($card_order))$list['data'][$key]['card_order'] = $card_order;
                    $order = db('order')->where($map)->field('add_time,order_sn,order_id')->find();
                    if(!empty($order))$list['data'][$key]['order'] = $order;
                }
            }
            return json($result = ['code'=>0,'msg'=>'获取成功','data'=>$list['data'],'count'=>$list['total']]);
        }
        return view('list2');
    }







    function choice($id = '',$str = ''){
        $materiel = $this->range();
        if($id==0){
            $str .= '<option level="1" value="0" selected>会员卡销售</option>';
        }else{
            $str .= '<option level="1" value="0" >会员卡销售</option>';
        }
        if($id==1){
            $str .= '<option level="1" value="1" selected>商品共享</option>';
        }else{
            $str .= '<option level="1" value="1">商品共享</option>';
        }
       if($id==2){
           $str .= '<option level="1" value="2" selected>商品销售</option>';
       }else{
           $str .= '<option level="1" value="2">商品销售</option>';
       }

        $str .= '<option level="2" value="2">&nbsp;&nbsp;所有品类</option>';
        foreach ($materiel as $key=>$v){
            if($id==$v['materiel_id']){
                $str .= '<option level="2" value="'.$v['materiel_id'].'" selected>&nbsp;&nbsp;&nbsp;&nbsp;'.$v['name'].'</option>';
            }else{
                $str .= '<option level="2" value="'.$v['materiel_id'].'" >&nbsp;&nbsp;&nbsp;&nbsp;'.$v['name'].'</option>';
            }

            if ($v['lower']) {
                foreach ($v['lower'] as $vvv) {
                    if($id==$vvv['materiel_id']){
                        $str .= '<option level="3" value="'.$v['materiel_id'].'" selected>&nbsp;&nbsp;&nbsp;&nbsp;'.$v['name'].'</option>';
                    }else{
                        $str .= '<option level="3" value="'.$vvv['materiel_id'].'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$vvv['name'].'</option>';
                    }
                }
            }
        }
        return $str;
    }



    function range(){
        $materiel = MModeL::where('parent_id=0')->column('materiel_id,name,parent_id');
        foreach ($materiel as $key=>$item){
            $materiel[$key]['lower'] = '';
             $lower = MModeL::where("parent_id={$item['materiel_id']}")->column('materiel_id,name,parent_id');
             if(!empty($lower))
            $materiel[$key]['lower'] = $lower;
        }
        return $materiel;
    }



    //推送优惠券
    function index3(){
        if ($this->request->isAjax()) {
            $key = input('key')?input('key'):'';
            $sj = input('sj')?input('sj'):'';
            if(!empty($sj)){
                $sj = explode(' - ',$sj);
                $where['r.create_time'] = array(array('egt',strtotime($sj[0])),array('elt',strtotime($sj[1]))) ;
            }

            $where['c.name'] = array('like','%'.trim($key).'%');

            $list = db('coupons_push')->alias('p')->join('je_coupons c','p.coupons_id = c.coupons_id')->field('c.name,c.scope,c.number,c.receive_number,c.start_time,c.settlement_time,p.push_id,p.create_time,p.user_id')->where($where)->order('push_id desc')->paginate(input('limit'))->toArray();

            foreach ($list['data'] as $key=>$v){
                if($v['scope']==0){
                    $scop = '会员卡';
                }elseif($v['scope']==1){
                    $scop = '共享商品';
                }elseif($v['scope']==2){
                    $scop = '销售商品';
                }else{
                    $scop = '销售商品--'.$name =  MModeL::where("materiel_id={$v['scope']}")->value('name');
                }
                $list['data'][$key]['coupons_id'] = '【'.$scop.'】'.$v['name'].'（'.date('Y-m-d',$v['start_time']).'至'.date('Y-m-d',$v['settlement_time']).'）';
                if($v['user_id']!='0'){
                    $userid = explode(',',$v['user_id']);
                    $list['data'][$key]['num'] = count($userid);
                    foreach ($userid as $k=>$item){
                        $username[] = db('user')->where("user_id = {$item}")->value('name');
                    }
                    $list['data'][$key]['user_id'] = implode(',',$username);
                    unset($username);
                }else{
                    $list['data'][$key]['num'] = db('user')->count();
                    $list['data'][$key]['user_id'] = '全部用户';
                }
                $list['data'][$key]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }
            return json($result = ['code'=>0,'msg'=>'获取成功','data'=>$list['data'],'count'=>$list['total']]);
        }
        return view('list3');
    }


    function add3(){
        if(request()->isPost()){
            $data = $this->request->post();
            if($data['user_id']=='' || $data['user_id']==1){
                return json(array('code' => 0, 'msg' => '推送失败,请选择推送对象'));
            }
            if(isset($data['coupons_id'])==false){return json(array('code' => 0, 'msg' => '推送失败,请选择推送优惠券'));}
            $coupons = CModeL::where("coupons_id = {$data['coupons_id']}")->field('receive_number,number,name')->find()->toArray();
            $num = $coupons['number']-$coupons['receive_number'];
            if($data['user_id']==0){
                $usercount = db('user')->count();
                if($usercount>$num){
                    return json(array('code' => 0, 'msg' => '推送失败,优惠券剩余数不足'));
                }
            }else{
                $user_id = explode(',',$data['user_id']);
                if(count($user_id)>$num){
                    return json(array('code' => 0, 'msg' => '推送失败,优惠券剩余数不足'));
                };
            }
            $data['create_time'] = time();

            Db::startTrans();
            try{
                db('coupons_push')->insert($data);
                $userId = db('coupons_push')->getLastInsID();

                if($data['user_id']==0){
                    $user = db('user')->field('user_id')->select();
                    $user_id = array_column($user,'user_id');
                }

                foreach ($user_id as $key=>$item){
                    $use['coupons_id'] = $data['coupons_id'];
                    $use['user_id'] = $item;
                    $use['receive_time'] = time();
                    $use['type'] = 1;
                    $use['push_id'] = $userId;
                    db('coupons_use')->insert($use);
                    db('coupons')->where('coupons_id', $data['coupons_id'])->setInc('receive_number');
                }
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                return json_encode(['code'=>0,'msg'=>'推送失败'.$e->getMessage()]);
            }

            return json(array('code'=>200,'msg'=>'推送成功'));
        }

        $list = CModeL::where('state',1)->whereTime('settlement_time', '>=', date('Y-m-d'))->column('coupons_id,name,scope,number,receive_number,start_time,settlement_time');
        foreach ($list as $key=>$item){
            if($item['scope']==0){
                $list[$key]['scope'] = '会员卡';
            }elseif($item['scope']==1){
                $list[$key]['scope'] = '共享商品';
            }elseif($item['scope']==2){
                $list[$key]['scope'] = '销售商品';
            }else{
                $list[$key]['scope'] = '销售商品--'.$name =  MModeL::where("materiel_id={$item['scope']}")->value('name');
            }
            $list[$key]['start_time'] = date('Y-m-d',$item['start_time']);
            $list[$key]['settlement_time'] = date('Y-m-d',$item['settlement_time']);
        }

        return view('add3',['list'=>$list]);
    }

    function edit3(){
        $id = input('id');
        $info = db('coupons_push')->alias('p')->join('je_coupons c','p.coupons_id = c.coupons_id')->field('c.name,c.scope,c.start_time,c.settlement_time,p.push_id,p.create_time,p.user_id')->where("p.push_id = {$id}")->find();

        if($info['scope']==0){
            $scop = '会员卡';
        }elseif($info['scope']==1){
            $scop = '共享商品';
        }elseif($info['scope']==2){
            $scop = '销售商品';
        }else{
            $scop = '销售商品--'.$name =  MModeL::where("materiel_id={$info['scope']}")->value('name');
        }
        $info['coupons_id'] = '【'.$scop.'】'.$info['name'].'（'.date('Y-m-d',$info['start_time']).'至'.date('Y-m-d',$info['settlement_time']).'）';

        if($info['user_id']!='0'){
            $userid = explode(',',$info['user_id']);
            $info['num'] = count($userid);
            foreach ($userid as $k=>$item){
                $username[] = db('user')->where("user_id = {$item}")->value('name');
            }
            $info['user_id'] = implode(',',$username);
        }else{
            $info['num'] = 0;
            $info['user_id'] = '全部用户';
        }

        $info['create_time'] = date('Y-m-d H:i:s',$info['create_time']);

        return view('edit3',['list'=>$info]);

    }
}